import threading
from event_engine.engine import *
from handlers.get_task_handler import GetTaskHandler
from handlers.download_handler import DownloadHandler
from handlers.proxy_ip_handler import ProxyIpHandler
from handlers.secondary_district_handler import SecondaryDistrictHandler
from handlers.secondary_circle_handler import SecondaryCircleHandler
from handlers.secondary_list_handler import SecondaryListHandler
from handlers.rent_district_handler import RentDistrictHandler
from handlers.rent_circle_handler import RentCircleHandler
from handlers.rent_list_handler import RentListHandler
from handlers.save_house_handler import SaveHouseHandler
from handlers.save_task_handler import SaveTaskHandler
from models.base import create_table
from models.task_queue import TaskQueue
from models.task import *

create_table()


class RunThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        # 实例化事件引擎
        engine = EventEngine(debug=False)

        # 注册事件
        engine.register(EVENT_GET_TASK, GetTaskHandler())
        engine.register(EVENT_GET_PROXY_IP, ProxyIpHandler())
        engine.register(EVENT_DOWNLOAD, DownloadHandler())
        engine.register(EVENT_SECONDARY_DISTRICT, SecondaryDistrictHandler())
        engine.register(EVENT_SECONDARY_CIRCLE, SecondaryCircleHandler())
        engine.register(EVENT_SECONDARY_LIST, SecondaryListHandler())
        engine.register(EVENT_RENT_DISTRICT, RentDistrictHandler())
        engine.register(EVENT_RENT_CIRCLE, RentCircleHandler())
        engine.register(EVENT_RENT_LIST, RentListHandler())
        engine.register(EVENT_SAVE_HOUSE, SaveHouseHandler())
        engine.register(EVENT_SAVE_TASK, SaveTaskHandler())

        # 启动事件引擎
        engine.run(lambda e: e.put(Event(EVENT_GET_TASK)))


def init_task():
    """
    添加初始任务
    """

    # 从这个网址找城市的二级域名 https://www.lianjia.com/city/
    city_list: list = [
        "https://dg.lianjia.com/",
        "https://fs.lianjia.com/",
        "https://gz.lianjia.com/",
        "https://hui.lianjia.com/",
        "https://jiangmen.lianjia.com/",
        "https://qy.lianjia.com/",
        "https://zh.lianjia.com/",
        "https://zhanjiang.lianjia.com/",
        "https://zs.lianjia.com/"
    ]

    for city_url in city_list:
        # 添加二手房任务
        TaskQueue.put(Task(
            type=TYPE_SECONDARY_DISTRICT,
            url=city_url + "ershoufang/",
        ))
        # 添加租房任务
        TaskQueue.put(Task(
            type=TYPE_RENT_DISTRICT,
            url=city_url + "zufang/",
        ))


if __name__ == '__main__':
    init_task()

    thread_number: int = 10  # 线程数
    thread_list: list = []  # 线程实例列表
    for i in range(thread_number):
        t = RunThread()
        thread_list.append(t)

    # 启动线程
    for t in thread_list:
        t.start()

    # 等待线程全部结束
    for t in thread_list:
        t.join()

    print("完成")
